<?php

namespace app\service;

use app\model\CartModel;
use app\model\GoodsModel;
use app\model\GoodsKuModel;
use Exception;

/**
 * 购物车服务类
 * 使用Laravel Eloquent ORM实现购物车相关业务逻辑
 */
class CartService
{
    /**
     * 添加商品到购物车
     * 
     * @param int $userId 用户ID
     * @param int $goodsId 商品ID
     * @param string $spec 商品规格
     * @param int $quantity 商品数量
     * @return array
     * @throws Exception
     */
    public function addToCart($userId, $goodsId, $spec, $quantity = 1)
    {
        // 验证商品是否存在
        $goods = GoodsModel::find($goodsId);
        if (!$goods) {
            throw new Exception('商品不存在');
        }

        // 验证规格是否存在
        $sku = GoodsKuModel::where('goods_id', $goodsId)
            ->where('specs', $spec)
            ->first();
        if (!$sku) {
            throw new Exception('商品规格不存在');
        }

        // 检查库存
        if ($sku->stock < $quantity) {
            throw new Exception('商品库存不足');
        }

        // 检查购物车是否已存在相同商品和规格
        $existingCart = CartModel::where('user_id', $userId)
            ->where('goods_id', $goodsId)
            ->where('spec', $spec)
            ->first();

        if ($existingCart) {
            // 更新数量
            $newQuantity = $existingCart->quantity + $quantity;
            if ($sku->stock < $newQuantity) {
                throw new Exception('商品库存不足');
            }
            
            $existingCart->update([
                'quantity' => $newQuantity,
                'updated_at' => time()
            ]);
            
            return [
                'cart_id' => $existingCart->id,
                'quantity' => $newQuantity,
                'message' => '更新购物车数量成功'
            ];
        } else {
            // 新增购物车记录
            $cart = CartModel::create([
                'user_id' => $userId,
                'goods_id' => $goodsId,
                'spec' => $spec,
                'quantity' => $quantity,
                'created_at' => time(),
                'updated_at' => time()
            ]);
            
            return [
                'cart_id' => $cart->id,
                'quantity' => $quantity,
                'message' => '添加到购物车成功'
            ];
        }
    }

    /**
     * 获取用户购物车列表（使用Eloquent关联）
     * 
     * @param int $userId 用户ID
     * @return array
     */
    public function getUserCartList($userId)
    {
        // 使用Eloquent关联加载相关数据
        $cartItems = CartModel::with(['goods', 'sku'])
            ->where('user_id', $userId)
            ->get();

        $totalPrice = 0;
        $totalQuantity = 0;
        $cartList = [];

        foreach ($cartItems as $item) {
            $price = $item->price; // 使用访问器获取价格
            $subtotal = $item->subtotal; // 使用访问器获取小计
            
            $cartList[] = [
                'cart_id' => $item->id,
                'quantity' => $item->quantity,
                'created_at' => $item->created_at,
                'goods_id' => $item->goods_id,
                'goods_name' => $item->goods ? $item->goods->title : '',
                'goods_image' => $item->goods ? $item->goods->image : '',
                'goods_price' => $item->goods ? $item->goods->price : 0,
                'sku_specs' => $item->spec,
                'sku_price' => $item->sku ? $item->sku->price : null,
                'sku_stock' => $item->sku ? $item->sku->stock : 0,
                'price' => $price,
                'subtotal' => $subtotal
            ];

            $totalPrice += $subtotal;
            $totalQuantity += $item->quantity;
        }

        return [
            'list' => $cartList,
            'total_price' => $totalPrice,
            'total_quantity' => $totalQuantity,
            'count' => count($cartList)
        ];
    }

    /**
     * 更新购物车商品数量
     * 
     * @param int $cartId 购物车记录ID
     * @param int $quantity 新的商品数量
     * @return array
     * @throws Exception
     */
    public function updateQuantity($cartId, $quantity)
    {
        $cart = CartModel::with(['sku'])->find($cartId);
        if (!$cart) {
            throw new Exception('购物车记录不存在');
        }

        // 验证库存
        if ($cart->sku && $cart->sku->stock < $quantity) {
            throw new Exception('商品库存不足');
        }

        $cart->update([
            'quantity' => $quantity,
            'updated_at' => time()
        ]);

        return [
            'cart_id' => $cartId,
            'quantity' => $quantity,
            'message' => '更新数量成功'
        ];
    }

    /**
     * 删除购物车商品
     * 
     * @param int $cartId 购物车记录ID
     * @return array
     * @throws Exception
     */
    public function removeFromCart($cartId)
    {
        $cart = CartModel::find($cartId);
        if (!$cart) {
            throw new Exception('购物车记录不存在');
        }

        $cart->delete();

        return [
            'cart_id' => $cartId,
            'message' => '删除成功'
        ];
    }

    /**
     * 清空用户购物车
     * 
     * @param int $userId 用户ID
     * @return array
     */
    public function clearUserCart($userId)
    {
        $deletedCount = CartModel::where('user_id', $userId)->delete();

        return [
            'deleted_count' => $deletedCount,
            'message' => '清空购物车成功'
        ];
    }

    /**
     * 获取用户购物车商品总数
     * 
     * @param int $userId 用户ID
     * @return int
     */
    public function getUserCartCount($userId)
    {
        return CartModel::where('user_id', $userId)->count();
    }

    /**
     * 批量操作购物车商品
     * 
     * @param int $userId 用户ID
     * @param array $cartIds 购物车记录ID数组
     * @param string $action 操作类型：'delete', 'select', 'unselect'
     * @return array
     */
    public function batchOperation($userId, $cartIds, $action)
    {
        if (empty($cartIds)) {
            throw new Exception('请选择要操作的商品');
        }

        $query = CartModel::where('user_id', $userId)
            ->whereIn('id', $cartIds);

        switch ($action) {
            case 'delete':
                $deletedCount = $query->delete();
                return [
                    'deleted_count' => $deletedCount,
                    'message' => '批量删除成功'
                ];
            
            case 'select':
                $updatedCount = $query->update(['selected' => 1]);
                return [
                    'updated_count' => $updatedCount,
                    'message' => '批量选择成功'
                ];
            
            case 'unselect':
                $updatedCount = $query->update(['selected' => 0]);
                return [
                    'updated_count' => $updatedCount,
                    'message' => '批量取消选择成功'
                ];
            
            default:
                throw new Exception('不支持的操作类型');
        }
    }

    /**
     * 获取购物车统计信息
     * 
     * @param int $userId 用户ID
     * @return array
     */
    public function getCartStats($userId)
    {
        $cartItems = CartModel::with(['goods', 'sku'])
            ->where('user_id', $userId)
            ->get();

        $stats = [
            'total_items' => $cartItems->count(),
            'total_quantity' => $cartItems->sum('quantity'),
            'total_price' => 0,
            'categories' => [],
            'brands' => []
        ];

        foreach ($cartItems as $item) {
            $subtotal = $item->subtotal;
            $stats['total_price'] += $subtotal;

            // 统计分类
            if ($item->goods && $item->goods->cat_id) {
                $catId = $item->goods->cat_id;
                if (!isset($stats['categories'][$catId])) {
                    $stats['categories'][$catId] = [
                        'count' => 0,
                        'quantity' => 0,
                        'price' => 0
                    ];
                }
                $stats['categories'][$catId]['count']++;
                $stats['categories'][$catId]['quantity'] += $item->quantity;
                $stats['categories'][$catId]['price'] += $subtotal;
            }
        }

        return $stats;
    }
}
